package com.goldsprite.gameframeworks.ecs.system.renderer;

import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.glutils.*;
import com.badlogic.gdx.utils.viewport.*;
import com.goldsprite.gameframeworks.ecs.component.*;
import com.goldsprite.gameframeworks.ecs.entity.*;
import com.goldsprite.gameframeworks.ecs.system.*;
import com.goldsprite.gameframeworks.log.Debug;
import com.goldsprite.gameframeworks.shaders.*;

import java.util.*;

@GameSystemInfo(
	type = GameSystemInfo.SystemType.UPDATE,
	interestComponents = {RenderableComponent.class}
)
public class SpriteRenderer extends RenderSystem {
	private final SpriteBatch batch;
	private final Viewport worldViewport, uiViewport;
	private FrameBuffer frameBuffer;
	private SpriteBatch bufBatch;
	public TextureRegion fboRegion;

	public SpriteRenderer() {
		batch = new SpriteBatch();

		// FBO创建
		worldViewport = GameSystem.worldViewport;
		uiViewport = GameSystem.uiViewport;

		// 只在视口有效时创建FBO
		if (uiViewport != null) {
			frameBuffer = new FrameBuffer(Pixmap.Format.RGBA8888,
				(int) worldViewport.getWorldWidth(),
				(int) worldViewport.getWorldHeight(), false);
			fboRegion = new TextureRegion(frameBuffer.getColorBufferTexture());
			fboRegion.flip(false, true);
			bufBatch = new SpriteBatch();
		}
	}

	@Override
	public void update(float delta) {
		if (!isEnabled()) return;

		// 渲染世界空间的精灵（使用世界相机）
		renderWorldSprites(delta);

		// 渲染UI空间的精灵（使用UI相机）
		renderUISprites(delta);
	}

	private void renderWorldSprites(float delta) {
		if (worldViewport == null) return;

		worldViewport.apply();
		batch.setProjectionMatrix(GameSystem.worldCamera.combined);

		ShaderProgram.pedantic = false;//*禁用严格检查
		batch.begin();

		renderEnts(delta);

		batch.end();
	}

	private void renderEnts(float delta) {
		// 获取所有可渲染实体
		List<GObject> renderableEntities = getInterestEntities();
		Debug.infoT("RendererSystem", "可渲染实体数: %s", renderableEntities.size());

		// 按渲染层顺序渲染世界空间的精灵
		for (String layer : RenderLayerManager.getSortedLayers()) {
			if (!RenderLayerManager.isLayerEnabled(layer) ||
				!RenderLayerManager.isWorldSpaceLayer(layer)) {
				continue;
			}

			for (GObject entity : renderableEntities) {
				// 检查物体是否启用
				if (!entity.isEnable()) continue;

				//TODO: 这里有问题, 只获取了实体的第一个可渲染组件, 1个以上会被忽略
				RenderableComponent sprite = entity.getComponent(RenderableComponent.class);
				if (sprite != null && layer.equals(sprite.getSpriteLayer())) {
					sprite.render(batch, delta);
				}
			}
		}
	}

	private void renderUISprites(float delta) {
		if (uiViewport == null) return;

		uiViewport.apply();
		batch.setProjectionMatrix(GameSystem.uiCamera.combined);
		batch.begin();

		// 获取所有可渲染实体
		List<GObject> renderableEntities = getInterestEntities();

		// 按渲染层顺序渲染UI空间的精灵
		for (String layer : RenderLayerManager.getSortedLayers()) {
			if (!RenderLayerManager.isLayerEnabled(layer) ||
				RenderLayerManager.isWorldSpaceLayer(layer)) {
				continue;
			}

			for (GObject entity : renderableEntities) {
				// 检查物体是否启用
				if (!entity.isEnable()) continue;

				SpriteComponent sprite = entity.getComponent(SpriteComponent.class);
				if (sprite != null && layer.equals(sprite.getSpriteLayer())) {
					sprite.render(batch, delta);
				}
			}
		}

		batch.end();
	}

	/**
	 * 刷新精灵的渲染层（当精灵的spriteLayer改变时调用）
	 */
	public void refreshSpriteLayer(RenderableComponent comp, String oldSpriteLayer) {
		// 在新的组件管理系统中，不需要特殊处理
		// 因为组件查询是动态的，每次update都会重新查询
		System.out.println("Sprite layer refreshed: " + oldSpriteLayer + " -> " + comp.getSpriteLayer());
	}

	/**
	 * 获取使用的SpriteBatch（用于外部设置着色器等）
	 */
	public SpriteBatch getBatch() {
		return batch;
	}

	public void dispose() {
		if (batch != null) {
			batch.dispose();
		}
		if (bufBatch != null) {
			bufBatch.dispose();
		}
		if (frameBuffer != null) {
			frameBuffer.dispose();
		}
	}
}
